package com.fsm_demo.syncDemo;

import ch.qos.logback.core.util.TimeUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/*******************
 *@Describe 实现一个读写缓存操作，没有加锁的情况
 *@author 封神梦
 *@Time 2022/6/24
 *@Company http://com.yiview.com
 ****************/
public class ReadWriteWithoutLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 0; i <=5 ; i++) {
            final Integer tempInt = i;
            new Thread(()->{
                myCache.put(tempInt.toString(),tempInt);
            },"写线程操作："+i).start();
        }
        for (int i = 0; i <=5 ; i++) {
            final Integer tempInt = i;
            new Thread(()->{
                myCache.get(tempInt.toString() );
            },"读线程操作："+i).start();
        }
    }

}
class MyCache {

    private volatile Map<String,Object> map  = new HashMap<>();

    public void put (String key,Object value){
        System.out.println(Thread.currentThread().getName()+"\t正在写入："+key);
        try{
            TimeUnit.MILLISECONDS.sleep(300);
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"\t写入完成："+value);
    }

    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"\t正在读取："+key);
        try{
            TimeUnit.MILLISECONDS.sleep(300);
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
        Object value = map.get(key);
        System.out.println(Thread.currentThread().getName()+"\t读取完成："+value);
    }

}
